{% extends "base.html" %}

{% block title %}统计报表{% endblock %}

{% block content %}
<div class="container-fluid">
    <div class="row">
        <!-- 左侧查询条件面板 -->
        <div class="col-md-3">
            <div class="card">
                <div class="card-header bg-primary text-white">
                    <h5 class="mb-0">查询条件</h5>
                </div>
                <div class="card-body">
                    <form id="statisticsForm" method="post">
                        <!-- 时间维度选择 -->
                        <div class="form-group mb-3">
                            <label for="timeDimension">时间维度</label>
                            <select class="form-select" id="timeDimension" name="time_dimension">
                                <option value="day">按日统计</option>
                                <option value="month">按月统计</option>
                                <option value="year">按年统计</option>
                                <option value="total">累计统计</option>
                            </select>
                        </div>

                        <!-- 时间范围选择 -->
                        <div class="form-group mb-3">
                            <label for="dateRange">时间范围</label>
                            <div class="input-group">
                                <input type="date" class="form-control" id="startDate" name="start_date">
                                <span class="input-group-text">至</span>
                                <input type="date" class="form-control" id="endDate" name="end_date">
                            </div>
                        </div>

                        <!-- 设备状态筛选 -->
                        <div class="form-group mb-3">
                            <label>设备状态</label>
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="statusInbound" name="status" value="在库" checked>
                                <label class="form-check-label" for="statusInbound">在库</label>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="statusOutbound" name="status" value="出库" checked>
                                <label class="form-check-label" for="statusOutbound">出库</label>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="statusDiscard" name="status" value="销库" checked>
                                <label class="form-check-label" for="statusDiscard">销库</label>
                            </div>
                        </div>

                        <!-- 分组方式选择 -->
                        <div class="form-group mb-3">
                            <label for="groupBy">分组方式</label>
                            <select class="form-select" id="groupBy" name="group_by">
                                <option value="type">按设备类型</option>
                                <option value="manufacturer">按制造商</option>
                                <option value="standard">按制式</option>
                                <option value="model">按型号</option>
                            </select>
                        </div>

                        <!-- 高级筛选 -->
                        <div class="accordion mb-3" id="advancedFilter">
                            <div class="accordion-item">
                                <h2 class="accordion-header">
                                    <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#advancedFilterContent">
                                        高级筛选
                                    </button>
                                </h2>
                                <div id="advancedFilterContent" class="accordion-collapse collapse">
                                    <div class="accordion-body">
                                        <div class="form-group mb-3">
                                            <label for="manufacturer">制造商</label>
                                            <select class="form-select" id="manufacturer" name="manufacturer">
                                                <option value="">全部</option>
                                                {% for m in manufacturers %}
                                                <option value="{{ m }}">{{ m }}</option>
                                                {% endfor %}
                                            </select>
                                        </div>
                                        <div class="form-group mb-3">
                                            <label for="type">设备类型</label>
                                            <select class="form-select" id="type" name="type">
                                                <option value="">全部</option>
                                                {% for t in types %}
                                                <option value="{{ t }}">{{ t }}</option>
                                                {% endfor %}
                                            </select>
                                        </div>
                                        <div class="form-group mb-3">
                                            <label for="standard">制式</label>
                                            <select class="form-select" id="standard" name="standard">
                                                <option value="">全部</option>
                                                {% for s in standards %}
                                                <option value="{{ s }}">{{ s }}</option>
                                                {% endfor %}
                                            </select>
                                        </div>
                                        <div class="form-group mb-3">
                                            <label for="model">型号</label>
                                            <select class="form-select" id="model" name="model">
                                                <option value="">全部</option>
                                                {% for m in models %}
                                                <option value="{{ m }}">{{ m }}</option>
                                                {% endfor %}
                                            </select>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- 查询按钮 -->
                        <div class="d-grid gap-2">
                            <button type="submit" class="btn btn-primary" id="queryBtn">
                                <i class="fas fa-search"></i> 查询
                            </button>
                            <button type="button" class="btn btn-success" id="exportBtn">
                                <i class="fas fa-file-excel"></i> 导出报表
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <!-- 右侧数据展示面板 -->
        <div class="col-md-9">
            <div class="card">
                <div class="card-header bg-primary text-white d-flex justify-content-between align-items-center">
                    <h5 class="mb-0">统计结果</h5>
                    <div class="btn-group">
                        <button type="button" class="btn btn-light btn-sm active" id="chartViewBtn">
                            <i class="fas fa-chart-bar"></i> 图表视图
                        </button>
                        <button type="button" class="btn btn-light btn-sm" id="tableViewBtn">
                            <i class="fas fa-table"></i> 表格视图
                        </button>
                    </div>
                </div>
                <div class="card-body">
                    <!-- 图表展示区域 -->
                    <div id="chartContainer" style="height: 400px;"></div>
                    
                    <!-- 表格展示区域 -->
                    <div id="tableContainer" style="display: none;">
                        <div class="table-responsive">
                            <table class="table table-striped table-hover">
                                <thead>
                                    <tr>
                                        <th>时间</th>
                                        <th>分组</th>
                                        <th>在库数量</th>
                                        <th>出库数量</th>
                                        <th>销库数量</th>
                                        <th>总计</th>
                                    </tr>
                                </thead>
                                <tbody id="statisticsTableBody">
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 引入 ECharts -->
<script src="https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js"></script>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // 初始化日期选择器
    const today = new Date();
    const lastMonth = new Date(today.getFullYear(), today.getMonth() - 1, today.getDate());
    document.getElementById('startDate').value = lastMonth.toISOString().split('T')[0];
    document.getElementById('endDate').value = today.toISOString().split('T')[0];

    // 初始化图表
    let chart = null;
    
    function initChart() {
        if (chart) {
            chart.dispose();
        }
        const chartDom = document.getElementById('chartContainer');
        chart = echarts.init(chartDom);
        console.log('Chart initialized');
    }

    // 初始化图表
    initChart();
    
    // 表单提交处理
    document.getElementById('statisticsForm').addEventListener('submit', function(e) {
        e.preventDefault();
        console.log('Form submitted');
        
        // 显示加载状态
        document.getElementById('chartContainer').innerHTML = '<div class="text-center"><div class="spinner-border" role="status"><span class="visually-hidden">Loading...</span></div></div>';
        
        // 获取表单数据
        const formData = new FormData(this);
        console.log('Form data:', Object.fromEntries(formData));
        
        // 发送AJAX请求
        fetch('/get_statistics', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(response => {
            console.log('Received response:', response);
            
            if (response.success) {
                // 重新初始化图表
                initChart();
                
                // 更新图表和表格
                updateChart(response.statistics);
                updateTable(response.statistics);
            } else {
                document.getElementById('chartContainer').innerHTML = '<div class="alert alert-danger">' + (response.message || '获取统计数据失败') + '</div>';
            }
        })
        .catch(error => {
            console.error('AJAX error:', error);
            document.getElementById('chartContainer').innerHTML = '<div class="alert alert-danger">请求失败：' + error.message + '</div>';
        });
    });

    // 更新图表
    function updateChart(statistics) {
        console.log('Updating chart with statistics:', statistics);
        
        if (!statistics || Object.keys(statistics).length === 0) {
            document.getElementById('chartContainer').innerHTML = '<div class="alert alert-info">暂无统计数据</div>';
            return;
        }

        const dates = Object.keys(statistics).sort();
        console.log('Dates:', dates);
        
        // 准备数据
        const series = [
            {
                name: '在库',
                type: 'bar',
                stack: 'total',
                emphasis: { focus: 'series' },
                data: []
            },
            {
                name: '出库',
                type: 'bar',
                stack: 'total',
                emphasis: { focus: 'series' },
                data: []
            },
            {
                name: '销库',
                type: 'bar',
                stack: 'total',
                emphasis: { focus: 'series' },
                data: []
            }
        ];

        // 处理每个时间点的数据
        dates.forEach(date => {
            const groups = statistics[date];
            console.log(`Processing date ${date}:`, groups);
            
            let inboundTotal = 0;
            let outboundTotal = 0;
            let discardTotal = 0;

            groups.forEach(group => {
                console.log(`Processing group:`, group);
                inboundTotal += parseInt(group.inbound_count) || 0;
                outboundTotal += parseInt(group.outbound_count) || 0;
                discardTotal += parseInt(group.discard_count) || 0;
            });

            console.log(`Totals for ${date}:`, { inboundTotal, outboundTotal, discardTotal });

            series[0].data.push(inboundTotal);
            series[1].data.push(outboundTotal);
            series[2].data.push(discardTotal);
        });

        console.log('Series data:', series);

        // 配置图表选项
        const option = {
            title: {
                text: '设备统计报表',
                left: 'center',
                top: 10
            },
            tooltip: {
                trigger: 'axis',
                axisPointer: { type: 'shadow' },
                formatter: function(params) {
                    let result = params[0].axisValue + '<br/>';
                    params.forEach(param => {
                        if (param.value > 0) {
                            result += param.seriesName + ': ' + param.value + '<br/>';
                        }
                    });
                    return result;
                }
            },
            legend: {
                data: ['在库', '出库', '销库'],
                top: 40
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                top: '100px',
                containLabel: true
            },
            xAxis: {
                type: 'category',
                data: dates,
                axisLabel: {
                    rotate: 45,
                    interval: 0
                }
            },
            yAxis: {
                type: 'value',
                name: '设备数量',
                nameLocation: 'middle',
                nameGap: 40
            },
            series: series,
            toolbox: {
                feature: {
                    saveAsImage: {},
                    dataZoom: {
                        yAxisIndex: 'none'
                    },
                    restore: {}
                },
                right: 20,
                top: 20
            },
            dataZoom: [
                {
                    type: 'slider',
                    show: true,
                    xAxisIndex: [0],
                    start: 0,
                    end: 100
                }
            ]
        };

        console.log('Chart option:', option);

        // 设置图表
        if (!chart) {
            console.log('Initializing new chart');
            initChart();
        }
        
        try {
            chart.setOption(option, true);
            console.log('Chart updated successfully');
        } catch (error) {
            console.error('Error updating chart:', error);
            document.getElementById('chartContainer').innerHTML = '<div class="alert alert-danger">图表更新失败：' + error.message + '</div>';
        }
    }

    // 获取状态颜色
    function getStatusColor(status) {
        const colors = {
            '在库': '#28a745',
            '出库': '#007bff',
            '销库': '#dc3545'
        };
        return colors[status] || '#6c757d';
    }

    // 更新表格
    function updateTable(statistics) {
        console.log('Updating table with statistics:', statistics);
        const tbody = document.getElementById('statisticsTableBody');
        tbody.innerHTML = '';

        if (!statistics || Object.keys(statistics).length === 0) {
            tbody.innerHTML = '<tr><td colspan="6" class="text-center">暂无统计数据</td></tr>';
            return;
        }

        Object.keys(statistics).sort().forEach(date => {
            statistics[date].forEach(group => {
                console.log(`Adding row for date ${date}, group:`, group);
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td>${date}</td>
                    <td>${group.group_name}</td>
                    <td>${group.inbound_count || 0}</td>
                    <td>${group.outbound_count || 0}</td>
                    <td>${group.discard_count || 0}</td>
                    <td>${group.total_count || 0}</td>
                `;
                tbody.appendChild(row);
            });
        });
    }

    // 窗口大小变化时调整图表大小
    window.addEventListener('resize', function() {
        if (chart) {
            chart.resize();
        }
    });

    // 视图切换按钮点击事件
    document.getElementById('chartViewBtn').addEventListener('click', function() {
        document.getElementById('chartContainer').style.display = 'block';
        document.getElementById('tableContainer').style.display = 'none';
        this.classList.add('active');
        document.getElementById('tableViewBtn').classList.remove('active');
        if (chart) {
            chart.resize();
        }
    });

    document.getElementById('tableViewBtn').addEventListener('click', function() {
        document.getElementById('chartContainer').style.display = 'none';
        document.getElementById('tableContainer').style.display = 'block';
        this.classList.add('active');
        document.getElementById('chartViewBtn').classList.remove('active');
    });

    // 导出按钮点击事件
    document.getElementById('exportBtn').addEventListener('click', function() {
        const formData = new FormData(document.getElementById('statisticsForm'));
        const params = new URLSearchParams(formData);
        window.location.href = '/export_statistics?' + params.toString();
    });

    // 初始加载数据
    document.getElementById('statisticsForm').dispatchEvent(new Event('submit'));
});
</script>
{% endblock %} 